import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { EChartComponent } from '../../shared/common/echarts/echarts.component';
import * as moment from 'moment';
import * as _ from 'lodash';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import {
  DailyReportServiceProxy,
  SearchInputReport
} from '../../../shared/service-proxies/service-proxies';

@Component({
  selector: 'app-month-report',
  templateUrl: './month-report.page.html',
  styleUrls: ['./month-report.page.scss']
})
export class MonthReportPage implements OnInit {

  monthDataParam: SearchInputReport = new SearchInputReport();//获取月报数据参数

  showNum: number = 0;
  yValue: number = 150;
  optionData: number = 0;
  id: string = "aaa";
  list: any;
  list3s: any;
  monthWaterOption: number = 5000;
  nowDate: any = new Date();
  sureTime: any = parseInt(moment(this.nowDate).format("YYYY"))
  nowDate1: any = new Date();
  monthValue: any = [];
  lastYear: any = parseInt(moment(this.nowDate).format("YYYY")) - 1 + "年";//去年的日期
  thisYear: any = parseInt(moment(this.nowDate).format("YYYY")) + "年";//今年的日期
  localdate: any = new Date(); //Sat Jul 20 2013 10:43:36 GMT+0800 (中国标准时间)
  lastYearDate: any = new Date(this.localdate - 365 * 24 * 60 * 60 * 1000);//去年的今天
  lastYearMonthList: any = [];
  lastYearMonthValue: any = [];

  constructor(
    private router: Router,
    private screenOrientation: ScreenOrientation,
    private _DailyReportServiceProxy: DailyReportServiceProxy,
  ) {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
  }

  ngOnInit() {
    this.getLastMonthBoardData();
    
    if (window.history && window.history.pushState) {
      $(window).on('popstate', function () {
        var hashLocation = location.hash;
        var hashSplit = hashLocation.split("#!/");
        var hashName = hashSplit[1];
        if (hashName !== '') {
          var hash = window.location.hash;
          if (hash === '') {
            alert("你点击了返回键");
          }
        }
      });
      window.history.pushState('forward', null, './#forward');
    }

  }

  //将要离开这个页面是触发
  ionViewWillLeave() {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  }

  goBack() {
    console.log(666)
    this.router.navigateByUrl('home');
  }


  changeShowNum() {
    if (this.showNum == 0) {
      this.showNum = 1;
      console.log("showNum", this.showNum);
    } else {
      this.showNum = 0;
      console.log("showNum", this.showNum);
    }
  }
  choosedTime() {
    this.thisYear = this.sureTime.year.value + "年";
    this.lastYear = this.sureTime.year.value - 1 + "年";
    this.nowDate1 = moment(this.sureTime.year.value + "-" + 12);
    this.monthDataParam.start = this.nowDate1;
    this.monthValue = [];
    this.lastYearMonthValue = [];
    this.lastYearDate = moment(this.sureTime.year.value - 1 + "-" + 12);
    this.getLastMonthBoardData();
    console.log("sureTime", this.sureTime);
    console.log("this.nowDate", this.nowDate);
    console.log("this.lastYearDate", this.lastYearDate);
  }

  subtractYValue() {
    this.lastYearMonthValue = [];
    this.monthValue = [];
    this.optionData = this.optionData - 500;
    this.getLastMonthBoardData();
  }
  addYValue() {
    this.lastYearMonthValue = [];
    this.monthValue = [];
    this.optionData = this.optionData + 500;
    this.getLastMonthBoardData();
  }
  suerNUm() {
    this.lastYearMonthValue = [];
    this.monthValue = [];
    this.optionData = this.optionData;
    this.getLastMonthBoardData();
  }

  //获取今年月供水量数据
  getMonthBoardData() {
    this.monthDataParam.start = this.nowDate1;
    this.monthDataParam.year = true;
    this.monthDataParam.tagfields = ["供水量"]
    this._DailyReportServiceProxy.searchWaterReport(this.monthDataParam)
      .subscribe((res) => {
        // let monthDataYear = moment(this.nowDate1).format("YYYY");
        // let lastyear = (parseInt(moment().format("YYYY")) - 1).toString();
        let grouped = _.groupBy(res, m => m.month);
        let result = _.uniq(res.map(m => m.month)).map(d => {
          let sum = _.sumBy(grouped[d], s => parseInt(s.value));
          let year = res.filter(m => m).map(m => m.year)[0];
          return {
            month: d,
            year: year,
            name: "月供水量",
            value: sum
          };
        });
        for (let l in result) {
          this.monthValue.push((result[l].value / 10000).toFixed(2));
        }
        this.monthWaterList()
      })
  }
  //获取去年月供水量数据
  getLastMonthBoardData() {
    let localdate: any = new Date(); //Sat Jul 20 2013 10:43:36 GMT+0800 (中国标准时间)
    let lastyear = new Date(localdate - 365 * 24 * 60 * 60 * 1000);
    this.monthDataParam.start = moment(this.lastYearDate);
    this.monthDataParam.year = true;
    this.monthDataParam.tagfields = ["供水量"]
    this._DailyReportServiceProxy.searchWaterReport(this.monthDataParam)
      .subscribe((res) => {
        let grouped = _.groupBy(res, m => m.month);
        let result = _.uniq(res.map(m => m.month)).map(d => {
          let sum = _.sumBy(grouped[d], s => parseInt(s.value));
          let year = res.filter(m => m).map(m => m.year)[0];
          return {
            month: d,
            year: year,
            name: "月供水量",
            value: sum
          };
        });
        for (let l in result) {
          this.lastYearMonthValue.push((result[l].value / 10000).toFixed(2));
        }
        this.getMonthBoardData();
      })
  }
  monthWaterList() {
    let self = this;
    this.list3s = {
      title: {
        text: '(单位：万m³)',
        textStyle: {      //标题颜色
          color: '#ffffff'
        },
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: [this.lastYear, this.thisYear],
        textStyle: {      //标题颜色
          color: '#ffffff'
        },
      },
      toolbox: {
        show: true,
        itemSize: 18,
        iconStyle: {
          color: "#f5f5f5",
          borderColor: "#f5f5f5"
        },
        feature: {
          dataView: { show: false, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'], color: "#f5f5f5" },
          restore: { show: false },
          saveAsImage: { show: false },
          myTool2: {
            show: true,
            title: '自定义扩展方法',
            icon: 'image://../../../assets/images/edit.png',
            onclick: function () {
              self.changeShowNum();
            }
          }
        },
      },
      xAxis: [
        {
          type: 'category',
          color: "#65b1eb",
          data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
          axisLabel: {
            textStyle: {
              color: '#ffffff'
            }
          },
          axisLine: {
            lineStyle: {
              type: 'solid',
              color: '#fff',//左边线的颜色
              width: '2',//坐标线的宽度,
              axisLabel: {
                textStyle: {
                  color: '#ffffff'
                }
              },
              axisLine: {
                lineStyle: {
                  type: 'solid',
                  color: '#fff',//左边线的颜色
                  width: '2'//坐标线的宽度
                }
              }
            }
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          min: this.optionData,
          axisLabel: {
            textStyle: {
              color: '#ffffff'
            }
          },
          axisLine: {
            lineStyle: {
              type: 'solid',
              color: '#fff',//左边线的颜色
              width: '2'//坐标线的宽度
            }
          }
        }
      ],
      series: [
        {
          name: this.lastYear,
          type: 'bar',
          color: '#65b1eb',
          min: 150,
          data: this.lastYearMonthValue,
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [
              { type: 'average', name: '平均值' }
            ]
          }
        },
        {
          name: this.thisYear,
          type: 'bar',
          color: '#75d999',
          min: 150,
          data: this.monthValue,
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [
              { type: 'average', name: '平均值' }
            ]
          }
        }
      ]
    }
  }
}
